#include <iostream>
#include <string>
#include <ctype.h>

#include "PurchaseMenu.h"

using std::string;
using std::cout;
using std::endl;
using std::cin;
using std::getline;

//Constructors

PurchaseMenu::PurchaseMenu(int itemType): InteractiveMenu("Purchase an item", "(You can enter -1 to return to the previous menu)")
{
	itemTypeID = itemType;
}

//Member Functions

void PurchaseMenu::performAction(Stock* companyStock, Cart* theCart)
{
	string itemID, quantityStr;
	int quantity;

	do {
		itemID = getItemIDFromUser();

		if (itemID.compare("-1") != 0)
		{
			int thisItemType = companyStock -> setBufferItem(itemID);

			if (thisItemType == -1)
				cout << "There is no item with ID " + itemID + "." << endl;
			else if (itemTypeID != 5 && thisItemType != itemTypeID)
				cout << "Item with ID " + itemID + " is not a " + companyStock -> getProductName(itemTypeID) + "." << endl;
			else
			{
				do {
					cout << "Please enter the quantity: ";
					getline(cin, quantityStr);

					if (quantityStr.compare("-1") != 0)
					{
						quantity = atoi(quantityStr.c_str());

						if (quantity <= 0)
							cout << "Invalid Input! ";
						else if (theCart -> purchaseItem(companyStock, itemID, quantity))
						{
							cout << quantity + " " + itemID + "(s) is/are successfully added into cart." << endl;
							quantityStr = "-1";
						}
						else
							cout << "The quantity required is more than that of the item in stock!" << endl;
					}
				} while (quantityStr.compare("-1") != 0);

				itemID = "-1";
			}
		}
	} while (itemID.compare("-1") != 0);

	cout << endl;
}